import { addAssetType, fetchTypeDetail, fetchTypeAttribute, addAttrToType } from '../services/api';

export default {
  namespace: 'assetType',

  state: {
    newType: undefined, // add type result
    typeAttr: [], // get type attribute result
    searchAttr: undefined, // search Attrubute result
    loading: true, // request fetching status
    typeInfo: undefined, // current type info
    submitLoading: false,
  },

  effects: {
    // step1 add a new type
    *saveType({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(addAssetType, payload);
      yield put({
        type: 'loadNewType',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      if (callback) {
        callback();
      }
    },
    // fetch type detail info
    *fetchType({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(fetchTypeDetail, payload);
      yield put({
        type: 'loadTypeDetail',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
    *submitTypeAttr({ payload, callback }, { call, put }) {
      yield ({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(addAttrToType, payload);
      yield ({
        type: 'changeLoading',
        payload: false,
      });
      yield put({
        type: 'loadTypeInfo',
        payload: response,
      });
      if (callback) {
        callback();
      }
    },
    // fetch type attributes
    *fetchTypeAttr({ payload, callback }, { call, put }) {
      yield ({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(fetchTypeAttribute, payload);
      yield put({
        type: 'loadTypeAttr',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });

      if (typeof callback === 'function') {
        callback();
      }
    },
  },

  reducers: {
    changeLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      };
    },
    submitLoading(state, { payload }) {
      return {
        ...state,
        submitLoading: payload,
      };
    },
    loadTypeDetail(state, { payload }) {
      return {
        ...state,
        typeInfo: payload.type_info,
      };
    },
    loadTypeAttr(state, { payload }) {
      return {
        ...state,
        typeAttr: payload.list,
      };
    },
    loadNewType(state, { payload }) {
      return {
        ...state,
        newType: payload,
      };
    },
  },
};
